package org.vgr.module.constraints;

import java.util.ArrayList;
import java.util.List;
import org.alfresco.service.cmr.repository.StoreRef;
import org.alfresco.model.ContentModel;
import org.alfresco.service.cmr.repository.NodeService;
import org.alfresco.service.cmr.search.ResultSet;
import org.alfresco.service.cmr.search.ResultSetRow;
import org.alfresco.service.cmr.search.SearchParameters;

public class LuceneSearchBasedListConstraint extends DynamicListConstraint {
    private static final long serialVersionUID = 1L;
    protected String searchLanguage;
    protected String query;
    protected String strStoreRef;

    public LuceneSearchBasedListConstraint() {}
    
    @Override
	protected List<String> getResult() {
    	this.logger();
        StoreRef storeRef = new StoreRef(strStoreRef);
        SearchParameters sp = createSearchParameters(storeRef);
        ResultSet resultSet = this.runQuery(sp);
        
        List<String> allowedValues = this.populateList(resultSet);
        
        return allowedValues;
    }

    protected NodeService getNodeService() {
    	return this.getServiceRegistry().getNodeService();
    }
    
    protected void logger() {
        if (logger.isDebugEnabled()) {
            logger.debug("Query:  " + query);
            logger.debug("Search Language:  " + searchLanguage);
            logger.debug("Store ref:  " + strStoreRef);
        }
    }
    
    protected SearchParameters createSearchParameters(StoreRef storeRef) {
    	 SearchParameters sp = new SearchParameters();
         sp.addStore(storeRef);
         sp.addSort("@cm:name", true);
         sp.setLanguage(this.searchLanguage);
         sp.setQuery(this.query);
         return sp;
    }
    
    protected List<String> populateList(ResultSet resultSet) {
        List<String> allowedValues = new ArrayList<String>();
        allowedValues.add("");
        for (ResultSetRow row : resultSet) {
        	String name = (String)this.getNodeService().getProperty(row.getNodeRef(), ContentModel.PROP_NAME);
        	String displayName = name;
            allowedValues.add(displayName);
        }
        
        return allowedValues;
    }
    
    protected ResultSet runQuery(SearchParameters sp) {
    	return this.getServiceRegistry().getSearchService().query(sp);
    }

    public void setQuery(String query) {
        this.query = query;
    }
    
    public void setSearchLanguage(String searchLanguage) {
        this.searchLanguage = searchLanguage;
    }

    public void setStoreRef(String storeRef) {
        this.strStoreRef = storeRef;
    }
}